package com.xbb.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xbb.config.JwtConfig;
import com.xbb.entity.User;
import com.xbb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 前端发送登录请求的时候，服务端返回一个token；前端再次发送其他请求的时候，要携带token，服务端验证通过后才可以获取请求数据。
 */
@RestController
public class LoginController {

    @Resource
    private JwtConfig jwtConfig ;

    @Autowired
    UserService userService;
    /*
     * 返参格式
     * {
     *     "userName": "1",
     *     "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxMSIsImlhdCI6MTU4OTIwMTMzNCwiZXhwIjoxNTg5MjA0OTM0fQ.9RdZ7-yRnSUM_QfixRNVW5n3hr2XV-YOd3vg0nwRzdaXLbvLVPmkLe5ixsSM4cVNlBdcJ6Swmvnnw3A57frDzw"
     * }
     */
    // 拦截器直接放行登录请求，返回Token
    @PostMapping("/login")
    public Map<String,Object> login (@RequestParam("loginName") String loginName,
                                     @RequestParam("password") String password){
        Map<String,Object> result = new HashMap<>() ;
        // 省略数据源校验
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("login_name",loginName).eq("password",password);
        //根据用户名和密码查询单个对象
        User one = userService.getOne(queryWrapper, false);
        if (one==null){
            result.put("code",501);
            result.put("msg","登录失败，用户名或密码不正确");
        }else {
            String token = jwtConfig.getToken(loginName+password) ;
            if (!StringUtils.isEmpty(token)) {
                result.put("token",token) ;
            }
            result.put("code",0);
            result.put("data",one);
        }
        return result ;
    }
    // 需要 Token 验证的接口
    @PostMapping("/info")
    public String info (){
        return "info" ;
    }
}
